package com.GLM.Viewer.Users;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.GLM.Constants.Constant;
import com.GLM.Tools.Utils.Image.AvatarUtil;
import com.GLM.Viewer.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class UserAvatarSelectActivity extends Activity{
	private Bitmap mDrawableAvater;
	private String takePhotoPath;
	private String fromalbumPath;
	private boolean takePhoto = false;
	private boolean fromAlbum = false;
	 public String photoName;
	 
	private String[] avatarNames = new String[]{
			"av2.png","av3.png","av4.png","av5.png","av6.png",
	};
	
	private int[] avatarIds = new int[]{
			R.drawable.av2, R.drawable.av3,
			R.drawable.av4, R.drawable.av5,R.drawable.av6
	};
	
	private int[] avatarBtnIds = new int[]{
			R.id.av1_btn, R.id.av2_btn, R.id.av3_btn,
			R.id.av4_btn, R.id.av5_btn, R.id.av6_btn
	};
	
	private Button[] avatarBtns;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_useravatar_select);
		
		initButtons();
	}
	
	private void initButtons(){
		avatarBtns = new Button[avatarBtnIds.length];
		
		for(int i=0; i<avatarBtns.length; i++){
			avatarBtns[i] = (Button)findViewById(avatarBtnIds[i]);
			final int index = i;
			avatarBtns[i].setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(index == avatarBtns.length -1){
						AlertDialog.Builder builder = new AlertDialog.Builder(UserAvatarSelectActivity.this);
						builder.setPositiveButton(getString(R.string.avater_album), new DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
								Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
								intent.addCategory(Intent.CATEGORY_OPENABLE);
								intent.setType("image/*");
								startActivityForResult(Intent.createChooser(intent, "Selete Picture"), Constant.ACTIVITY_REQUESTCODE_ALBUM);
							}
						});
						builder.setNeutralButton(getString(R.string.avater_takepicture), new DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
								Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
								startActivityForResult(intent, Constant.ACTIVITY_REQUESTCODE_TAKEPICTURE);
							}
						});
						builder.setNegativeButton(getString(R.string.cancel), null);
						builder.setTitle(getString(R.string.newparty_tips_dialog));
						builder.show();
					}else{
						Intent intent = new Intent(UserAvatarSelectActivity.this,UserSettingActivity.class);
						intent.putExtra("photoResourceId", avatarIds[index]);
						intent.putExtra("photoName", avatarNames[index]);
						setResult(RESULT_OK, intent);
						finish();
					}
				}
			});
		}
		
		
	}
	
	private String checkImagePath(Intent data){
		Cursor cursor = null;
		String path = null;
		try {
			Uri originalUri = data.getData();
			path = originalUri.toString();
			String[] proj = { MediaStore.Images.Media.DATA };
			cursor = managedQuery(originalUri, proj, null, null, null);
			if (cursor != null) {
				int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				// 最后根据索引值获取图片路径
				path = cursor.getString(column_index);
				Log.d("checkImagePath_path", path);
			}
		}
	    catch (Exception e) {
			Log.e("checkImage", e.getMessage());
		} finally {
			if (cursor != null && !cursor.isClosed()) 
				cursor.close();
		}
		
		return path;		
	}
	
	public static String formatDatetime(Date date, String format) {  
        DateFormat df = new SimpleDateFormat(format);  
        return df.format(date);  
    }  
	
	
	
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, Constant.ACTIVITY_REQUESTCODE_NEWAVATER);
	}
	
	 public void WriteImage() {  
	        try {  
	            FileInputStream fis = new FileInputStream(takePhotoPath);  
	            ByteArrayOutputStream baos = new ByteArrayOutputStream();  
	            byte[] buffer = new byte[8192];  
	            int count = 0;  
	            while ((count = fis.read(buffer)) >= 0) {  
	                baos.write(buffer, 0, count);  
	  
	            }  
	            fis.close(); 
	            
	        } catch (FileNotFoundException e) {  
	            e.printStackTrace();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	 }  
	
	 
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(resultCode == RESULT_OK){
			switch (requestCode) {
			case Constant.ACTIVITY_REQUESTCODE_ALBUM:
				String str = checkImagePath(data);
				if(str != null){
					takePhoto = false;
					fromAlbum = true;
					String end = str.substring(str.lastIndexOf("."));
					int endindex = str.lastIndexOf("/")+1;
					String fpath = str.substring(0, endindex);
					File file = new File(str);
					String filename = formatDatetime(new Date(), "yyyyMMddHHmmsssss")+end;
					File newFile = new File(fpath+filename);
					file.renameTo(newFile);
					
					fromalbumPath = newFile.getAbsolutePath();
					Log.d("fromalbum", fromalbumPath);
					photoName = filename;
					Log.d("photoName", photoName);
					Log.d("ImageChoosepath", str);
				}
				startPhotoZoom(data.getData());
				break;
			case Constant.ACTIVITY_REQUESTCODE_TAKEPICTURE:
				String status = Environment.getExternalStorageState();
				if(!status.equals(Environment.MEDIA_MOUNTED)){
					Toast.makeText(UserAvatarSelectActivity.this, getString(R.string.sdcard_notin), Toast.LENGTH_LONG).show();
					return ;
				}
				Uri uri = data.getData();
				if(uri != null){
					mDrawableAvater = BitmapFactory.decodeFile(uri.getPath());
				}
				if(mDrawableAvater == null){
					Bundle bundle = data.getExtras();
					if(bundle != null){
						mDrawableAvater =  (Bitmap)bundle.get("data");
					}else{
						Toast.makeText(UserAvatarSelectActivity.this, "获取照片失败", Toast.LENGTH_LONG).show();
						return;
					}
				}
				
				FileOutputStream outputStream = null;
				photoName = formatDatetime(new Date(), "yyyyMMddHHmmsssss")+".jpg";
				String dirstr = Environment.getExternalStorageDirectory().toString() +"/glemei";
				File dir = new File(dirstr);
				
				if (!dir.exists()) {
					dir.mkdir(); 
				}
				File file = new File(dirstr, photoName);
				try {
					file.createNewFile();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				takePhotoPath = file.getAbsolutePath();
				Log.d("takePhotoPath", takePhotoPath);
				try {
					outputStream = new FileOutputStream(takePhotoPath);
					mDrawableAvater.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
					
				} catch (Exception e) {
					// TODO: handle exception
				}
				Log.d("beginWriteImage", "begin");
				WriteImage();
				takePhoto = true;
				fromAlbum = false;
				Intent intent = new Intent(UserAvatarSelectActivity.this, UserSettingActivity.class);
				intent.putExtra("takephoto", true);
				intent.putExtra("photoName", photoName);
				intent.putExtra("photoPath", takePhotoPath);
				setResult(RESULT_OK, intent);
				finish();
//				avatarBtns[avatarBtnIds.length-1].setBackgroundDrawable(AvatarUtil.Bitmap2Drawable(mDrawableAvater));
				break;
			case Constant.ACTIVITY_REQUESTCODE_NEWAVATER:
				
				Intent avaIntent = new Intent(UserAvatarSelectActivity.this, UserSettingActivity.class);
				avaIntent.putExtra("takephoto", false);
				avaIntent.putExtra("photoName", photoName);
				avaIntent.putExtra("photoPath", fromalbumPath);
				setResult(RESULT_OK, avaIntent);
				finish();
//				Drawable newAvater = getNewAvater(data);
//				
//				if (newAvater != null) {
//					mDrawableAvater = ((BitmapDrawable) newAvater).getBitmap();
//					avatarBtns[avatarBtnIds.length-1].setCompoundDrawables(newAvater, null, null, null);
//				}
				break;	
			
			default:
				break;
			}
		}
		
	}
	
	private Drawable getNewAvater(Intent data) {
		if (null != data) {
			Bundle bundle = data.getExtras();
			if (null != bundle) {
				Bitmap photo = bundle.getParcelable("data");
				
				Drawable drawable = new BitmapDrawable(photo);
				drawable.setBounds(0, 0, 100, 100);
				return drawable;
			}
		}
		return null;

	}
	public void gobackButton_OnClick(View v){
		NavUtils.navigateUpFromSameTask(this);
	}
}
